package com.douwong.student.task;

import android.os.AsyncTask;
import android.util.Log;

import com.douwong.student.model.StatusCode;
import com.douwong.student.rxjava.NetWork;
import com.douwong.student.utils.DateTools;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.UIUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;

/**
 * 上传设备日志信息
 * 
 * @author leihuajie
 * 
 */
public class UpLoadDeviceLogTask extends AsyncTask<String, Integer, String> {

	private String TAG="UpLoadDeviceLogTask";
	private final int LIMITFILESIZE=10;
	private String iniPath= FileUtils.APP_CRASH+"/crash.ini";
	private Subscription mSubscription;

	public UpLoadDeviceLogTask(){


	}
	
	@Override
	protected String doInBackground(String... params) {
		String response = null;
		if(!NetUtils.NetwrokIsUseful(UIUtils.getContext())){
			return response;
		}
		try {
			checkAndCommitCrashLog();
			//删除多余日志，暂时不提交
			checkFunctionLog();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private void checkFunctionLog() throws Exception{

	 	File[] files=new File(FileUtils.APP_LOG).listFiles();
//		Log.d(TAG,"文件数量 ： "+files.length);
		int overcount=files.length-LIMITFILESIZE;
		if(overcount>0){
//			Log.d(TAG,"删除日志数量 ： "+overcount);
			TreeMap<Long,File> fileMap=new TreeMap<Long, File>();
			for(File file:files){
				fileMap.put(file.lastModified(),file);
			}
			Iterator<Long> keys=fileMap.keySet().iterator();
			Long[] removeKeys=new Long[overcount];
            for(int i=0;i<overcount;i++){
				Long key=keys.next();
				removeKeys[i]=key;
			}
			for(Long rkey:removeKeys){
				fileMap.get(rkey).delete();
			}

		}
	}


	private void checkAndCommitCrashLog() throws Exception{
		boolean flushCacheMode=false;
		File iniFile=new File(iniPath);

		if(!iniFile.exists()){
			try {
				iniFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//检查错误日志并上传（当天的日志文件不上传）
		File[] files=new File(FileUtils.APP_CRASH).listFiles(new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				// TODO Auto-generated method stub
				String fname=pathname.getName();
				String day=fname.substring(fname.indexOf("_")+1, fname.lastIndexOf("."));
				if(fname.endsWith(".log")&&!day.equals(DateTools.getCrashDay())){
					return true;
				}
				return false;
			}
		});
		Properties properties=FileUtils.readConfigPrt(iniPath);

		if(properties!=null){
			ArrayList<File> results=new ArrayList<File>();
			Set<String> keys=properties.stringPropertyNames();
			for(File file:files){
				String fname=file.getName();
				if(keys.contains(fname)){
					if(properties.getProperty(fname).equals("1")){
						if(files.length>LIMITFILESIZE){
							flushCacheMode=true;
							file.delete();
							properties.remove(fname);
						}
					}else{
						//前期提交失败的
						results.add(file);
					}
				}else{
					//新增记录
					properties.setProperty(fname, "0");
					results.add(file);
				}
			}

			if(flushCacheMode){
				FileUtils.saveConfigPrt(properties, iniPath);
			}
			if(!results.isEmpty()){
				commitFiles(results, properties);
			}
		}
	}

	private void commitFiles(final ArrayList<File> files,final Properties properties) throws Exception{
		if (mSubscription!=null &&!mSubscription.isUnsubscribed()){
			mSubscription.unsubscribe();
		}
		Map<String,RequestBody> photos = new HashMap<>();
		for (File file:files) {
			RequestBody photo = RequestBody.create(MediaType.parse("multipart/form-data"), file);
			photos.put("logFile\"; filename=\""+file.getName(), photo);
		}

/*		Map<String,RequestBody> photos = new HashMap<>();
		photos.put("photos\"; filename=\"icon.png", photo);
		photos.put("username",  RequestBody.create(null, "abc"));*/

		mSubscription = NetWork.getHeadEndPointInterface()
				.uploadErrorLog(photos,RequestBody.create(null,"737"),RequestBody.create(null,"1"))
		.subscribeOn(Schedulers.io())
		.observeOn(Schedulers.io())
		.subscribe(new Subscriber<StatusCode<String>>() {
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {
				Log.i(TAG, "onError "+e.toString());
			}

			@Override
			public void onNext(StatusCode<String> stringStatusCode) {
				Log.i(TAG, "onNext "+stringStatusCode);
				if(stringStatusCode.isFlag()){
					//更新crash.ini，记录已经提交的文件
					for(File file:files){
						properties.setProperty(file.getName(),"1");
					}
					FileUtils.saveConfigPrt(properties, iniPath);
				}
			}
		});

	/*	HashMap<String, String> params=new HashMap<String, String>();
		params.put("logFileType", "1");
		params.put("deviceType", "737");
		try {
			String result= SocketHttpRequester.post(NetConfig.UPLOAD_DEVICE_LOG.toString(), params, files);
			Boolean flag= JSON.parseObject(result).getBoolean("flag");
			
			if(flag){
				//更新crash.ini，记录已经提交的文件
				for(File file:files){
				  	properties.setProperty(file.getName(),"1");
				}				
				FileUtils.saveConfigPrt(properties, iniPath);				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}*/
		
	 }

}
